﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ComponentModel.Composition.Extensions.Web;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Primitives;
using System.Web;

namespace Steve.UI
{
    public static class ScopedContainerManagerExtensions
    {
        public static T GetExportedValue<T>(this ScopedContainerManager container)
        {
            if (container == null) throw new ArgumentNullException("container");

            var contextItems = container.GetCurrentContext().Items;
            using (var child = new CompositionContainer(container.GetRequestContainer(contextItems)))
            {
                return child.GetExportedValue<T>();
            }
        }

        public static IEnumerable<T> GetExportedValues<T>(this ScopedContainerManager container)
        {
            if (container == null) throw new ArgumentNullException("container");

            var contextItems = container.GetCurrentContext().Items;
            using (var child = new CompositionContainer(container.GetRequestContainer(contextItems)))
            {
                return child.GetExportedValues<T>();
            }
        }

        public static T Compose<T>(this ScopedContainerManager container) where T : new()
        {
            if (container == null) throw new ArgumentNullException("container");

            var obj = new T();
            container.Compose(obj);
            return obj;
        }

        public static void Compose<T>(this ScopedContainerManager container, T obj)
        {
            if (container == null) throw new ArgumentNullException("container");

            var contextItems = container.GetCurrentContext().Items;
            using (var child = new CompositionContainer(container.GetRequestContainer(contextItems)))
            {
                child.ComposeParts(obj);
            }
        }

        internal static HttpContextBase GetCurrentContext(this ScopedContainerManager container)
        {
            if (container == null) throw new ArgumentNullException("container");

            using (var child = new CompositionContainer(container.ApplicationContainer))
            {
                var builder = child.GetExportedValue<IHttpContextBaseBuilder>();
                return builder.BuildCurrent();
            }
          
        }
    }
}
